from django import forms
from .models import Userinfo

class RegistrationForm(forms.Form):
    username = forms.CharField(label='username',max_length=50)
    password = forms.CharField(label='Password',widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if len(username) < 6:
            raise forms.ValidationError("用户名必须至少6个字符！")
        elif len(username) > 50:
            raise forms.ValidationError("用户名太长！")
        else:
            filter_result = Userinfo.objects.get(username=username)
            if len(filter_result) > 0:
                raise forms.ValidationError("用户名已存在!")
        return username

    def clean_pwd(self):
        password = self.cleaned_data.get('password')
        if len(password) < 6:
            raise forms.ValidationError("密码太短！")
        elif len(password) > 20:
            raise forms.ValidationError("密码太长！")
        return password

class LoginForm(forms.Form):
    username = forms.CharField(label='username',max_length=50)
    password = forms.CharField(label='password',widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if len(username) < 0:
            raise forms.ValidationError("用户名不能为空")
        else:
            filt_result = Userinfo.objects.filter(username=username)
            if not filt_result:
                raise forms.ValueError("用户名不存在！")
            else:
                return username

    def clean_password(self):
        password = self.cleaned_data.get("password")
        if len(password) < 0:
            raise forms.ValidationError("密码不能为空！")
        else:
            return password
